package cn.tworice.common.util;

import cn.tworice.common.vo.RequestResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

public class RequestUtil {

    public static final String ENCODING = "UTF-8";

    public static final String CONTENT_TYPE = "text/html; charset=utf-8";

    public static HttpServletRequest getHttpServletRequest() {
        return (
                (ServletRequestAttributes)
                Objects.requireNonNull(
                        RequestContextHolder.getRequestAttributes()
                )).getRequest();
    }

    public static void returnJson(HttpServletResponse response, RequestResult message){
        response.setCharacterEncoding(RequestUtil.ENCODING);
        response.setContentType(RequestUtil.CONTENT_TYPE);
        String jsonString = JSON.toJSONString(message);
        try (PrintWriter writer = response.getWriter()) {
            writer.print(jsonString);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
